package com.example.server.util;

import com.example.server.pojo.File;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class DealFiles {
    @Value("${uploadfile.path}")
    private String filepath;

    public File dealFile(MultipartFile multipartFile){
        File file=new File();
        String uuid="-1";
        String filetype=null;
        String filename=null;
        String filehead=null;
        String fileend=null;
        Date createdate=null;
        String today=null;
        long filesize=0;
        String fileallpath=null;
        if(multipartFile!=null){
            //文件原名
            filename=multipartFile.getOriginalFilename();
            //文件类型
            filetype=filename.split("\\.")[filename.split("\\.").length-1];
            fileend="."+filetype;
            //处理掉后缀的文件名
            filehead=filename.replace(fileend,"");
            //文件大小
            filesize=multipartFile.getSize();
            //文件名的uuid
            uuid=UUID.randomUUID().toString();
            //计算当前日期
            today=new SimpleDateFormat("yyyyMMdd").format(new Date());
            //创建文件
            java.io.File file1=new java.io.File(filepath+"\\"+today);
            if(!file1.isDirectory()){
                file1.mkdir();
            }
            //文件完整路径
            fileallpath=filepath+"\\"+today+"\\"+uuid+fileend;
            System.out.println(fileallpath);
            java.io.File file2=new java.io.File(fileallpath);
            try {
                if (!file2.exists()) {
                    createdate=new Date();
                    multipartFile.transferTo(file2);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            file.setFileName(filehead);
            file.setFilePath(fileallpath);
            file.setFileType(filetype);
            file.setUuid(uuid);
            file.setFileSize(filesize);
            file.setCreateTime(createdate);
        }else {
            file.setUuid("-1");
        }
        return file;
    }

}
